/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios';
import {serialize} from '@/util/util';
import {
    removeEntry,
    removeToken,
    removeUserAuthority,
    removeTenantInfo,
    removeConfig,
    setUserInfo,
    getToken} from '@/util/auth';
import {Message} from 'element-ui';
import website from '@/config/website';
import NProgress from 'nprogress';
import router from './router.js';

//默认超时时间
axios.defaults.timeout = 60000;
//返回其他状态码
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500;
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// NProgress 配置
NProgress.configure({
  showSpinner: false
});
//http request拦截
axios.interceptors.request.use(config => {
  // debugger;
  //开启 progress bar
  NProgress.start();
  const meta = (config.meta || {});
  const isToken = meta.isToken === false;
  // config.headers['Authorization'] = `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}`;
  if (getToken() && !isToken) {
    //让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    config.headers['Auth-Token'] = getToken()
  }
  //headers中配置serialize为true开启序列化
  if (config.method === 'post' && meta.isSerialize === true) {
    config.data = serialize(config.data);
  }
  return config
}, error => {
  return Promise.reject(error)
});
//http response 拦截
axios.interceptors.response.use(res => {
  let data = res.data.data
  // debugger;
  if(data){
    if (data.total) data.total = data.total * 1
    if (data.size) data.size = data.size * 1
    if (data.current) data.current = data.current * 1
  }

  //关闭 progress bar
  NProgress.done();
  //获取状态码
  const status = res.data.code || res.data.Code || res.Status;
  const statusWhiteList = website.statusWhiteList || [];
  // const message = res.data.Msg || res.data.msg || res.data.error_description || '未知错误';
  //如果在白名单里则自行catch逻辑处理
  if (statusWhiteList.includes(status)) return Promise.reject(res);
  const message =res.data.msg||res.data.Msg;
  //如果是401则跳转到登录页面
  if (status === 401 || res.status === 401){
        Message({
          message: message,
          type: 'error'
        });
      removeToken();
      removeUserAuthority();
      removeTenantInfo();
      removeConfig();
      setUserInfo(null);
        router.push({path: '/login'});
        return Promise.reject(new Error(message))
      // return res;
  }
    // store.dispatch('FedLogOut').then(() => router.push({path: '/login'}));
  // 如果请求为非200否者默认统一处理
  // if (status !== 200) {
  //   Message({
  //     message: message,
  //     type: 'error'
  //   });
  //   router.push({path: '/login'});
  //   return Promise.reject(new Error(message))
  // }
  return res;
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
});

export default axios;
